import React from 'react';
import { Spin, Transfer } from 'antd';

export default class RolePermissionEdit extends React.Component {
  componentDidMount() {
    const { dispatch, modularName, data = {} } = this.props;

    dispatch({
      type: `${modularName}/queryRolePermission`,
      payload: { roleId: data.roleId }
    });
  }

  componentWillUnmount() {
    const { dispatch, modularName } = this.props;

    dispatch({
      type: `${modularName}/changeState`,
      payload: { menus: [], rolePermission: [] }
    });
  }

  handleChange = (targetKeys, direction, moveKeys) => {
    const { dispatch, modularName } = this.props;

    dispatch({
      type: `${modularName}/changeState`,
      payload: {
        rolePermission: targetKeys
      }
    });
  }

  dataSourceIteration(data, level = 0) {
    const result = [];

    if (Array.isArray(data) && data.length > 0) {
      data.forEach(element => {
        const { children, ...extra } = element;

        result.push({ ...extra, key: element.id, level });
        result.push(...this.dataSourceIteration(children, level + 1));
      });
    }
    return result;
  }

  targetIteration(data, targetKeys) {
    const result = [];

    if (Array.isArray(data) && data.length > 0) {
      data.forEach(element => {
        if (targetKeys.indexOf(element.id) !== -1) {
          result.push(element.id);
        }
        const { children } = element;
        result.push(...this.targetIteration(children, targetKeys));
      });
    }
    return result;
  }

  renderItem(item) {
    const customLabel = (
      <span>
        {item.code} - {item.name}
      </span>
    );

    return {
      label: customLabel,
      value: `${item.code} - ${item.name}`,
    };
  }

  render() {
    const { loading, menus = [], rolePermission = [] } = this.props;
    const orderMenu = this.dataSourceIteration(menus);

    return (
      <Spin spinning={loading}>
        <Transfer
          dataSource={orderMenu}
          listStyle={{
            width: 365,
            height: 400,
          }}
          showSearch
          targetKeys={this.targetIteration(orderMenu, rolePermission)}
          titles={['未分配', '已分配']}
          onChange={this.handleChange}
          render={this.renderItem}
        />
      </Spin>
    );
  }
}